﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FalionForm
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
    public MainWindow()
        {
            
            this.Visibility = Visibility.Hidden;          
            InitializeComponent();
            mainWindow = this;       
            test.Width = 768 * SystemParameters.PrimaryScreenWidth / SystemParameters.PrimaryScreenHeight;
            this.Width = 768 * SystemParameters.PrimaryScreenWidth / SystemParameters.PrimaryScreenHeight;

            ThreadRun(Login);//多线程耗时
            time.TimeDisp += Time_TimeDisp;//事件订阅
            InitializeData();//数据初始化

            this.GridPage.Navigate(mp);
            MainPage.pro.mw = this;
        }

        public static SocketClient SClient=new SocketClient();
        private void InitializeData()//数据初始化
        {
            NodeX ns1 = new NodeX() { Name = "参数列表", Icon = "\ue633", FrontSize = 12 };
            ns1.Nodes = new List<NodeX>();
            ns1.Nodes.Add(new NodeX() { Name = "新增列表", Icon = "\ue633", FrontSize = 10 });
            ns.Add(ns1);
            ns.Add(new NodeX() { Name = "配置", Icon = "\ue622", FrontSize = 12 });
            ns.Add(new NodeX() { Name = "配置", Icon = "\ue655", FrontSize = 12 });
            ns.Add(new NodeX() { Name = "配置", Icon = "\ue66f", FrontSize = 12 });
            this.tree.ItemsSource = ns;
            time.mv = this;
        }
        BusyWindow busyWindow;//等待状态
        public MainWindow mainWindow;
        
        ProgramData programData = new ProgramData();

        MainPage mp = new MainPage();
        
        Page1 pg = new Page1();
        Page2 pm = new Page2();
        Page3 pn = new Page3();
        List<NodeX> ns = new List<NodeX>();





        private void Login()//模拟启动耗时操作
        {
                    
            Thread.Sleep(1000);
            this.Dispatcher.Invoke(new Action(() =>{
                this.Visibility = Visibility.Visible;
                ChangePic(PublicData.publicData.loginData.UserTypes);
            }));
        }






        public static bool adminflg = false;

        //按钮事件
        public void Close_Click(object sender, RoutedEventArgs e)//关闭软件
        {
            TextRange TR = new TextRange(dispMess.Document.ContentStart, dispMess.Document.ContentEnd);
            string str = TR.Text;


            dt = DateTime.Now;
            string strd = dt.Date.Month + "-" + dt.Date.Day;
            strd = strd + "_" + dt.Hour + "_" + dt.Minute+".txt";

            
            try
            {
                System.IO.File.WriteAllText(@"Log\" + strd, str, Encoding.UTF8);
            }
            catch 
            {


            }
            this.Close();
        }
        private void User_Set(object sender, RoutedEventArgs e)//用户设置
        {
            LoginWindow LW = new LoginWindow();
            LW.mainWindow = this;
            LoadingAdorner.IsAdornerVisible = true;
            adminflg=(bool)LW.ShowDialog();
            LoadingAdorner.IsAdornerVisible = false;
        }
        private void Language_click(object sender, RoutedEventArgs e)//语言切换
        {
            MenuItem Menu = (MenuItem)sender;
            switch (Menu.Header.ToString())
            {
                case "中文":
                    App.Culture = "zh-CN";
                    break;
                case "English":
                    App.Culture = "en-US";
                    break;
                case "日本語":
                    break;
                case "한글":
                    break;
                default:
                    break;
            }
            App.UpdateCulture();
        }
        private void Btn_Click(object sender, RoutedEventArgs e)//切换页面
        {
            Util.Controls.FButton Fb = (Util.Controls.FButton)sender;
           
            switch (Fb.Name)
            {              
                case "run":
                    this.GridPage.Navigate(mp);
                    break;
                case "set":
                    this.GridPage.Navigate(programData);
                    break;
                case "con":
                    this.GridPage.Navigate(pn);
                    break;
                default:
                    break;
            }
        }
        private void Tree_click(object sender, MouseButtonEventArgs e)
        {

        }

        private void TooL_Clik(object sender, RoutedEventArgs e)
        {
            MenuItem Fb = (MenuItem)sender;
            switch (Fb.Name)
            {
                case "screen":
                    #region screen
                    string path = DateTime.Now.ToString("yyyy_MM_dd HH_mm_ss") + ".bmp";
                    try
                    {
                        Bitmap bit = new Bitmap((int)((this.Width/1366)* SystemParameters.PrimaryScreenWidth), (int)((this.Height/768) * SystemParameters.PrimaryScreenHeight));
                        Graphics g = Graphics.FromImage(bit);
                        g.CopyFromScreen(new System.Drawing.Point((int)this.Left, (int)this.Top), new System.Drawing.Point(0, 0), bit.Size);
                        bit.Save(path);                       
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    #endregion
                    break;
                case "connect":
                    System.Diagnostics.Process.Start("taskmgr.exe");
                    break;
                case "network":
                    System.Diagnostics.Process.Start("ncpa.cpl");
                    break;
                case "calculate":
                    System.Diagnostics.Process.Start("calc.exe");
                    break;
                case "paint":
                    System.Diagnostics.Process.Start("mspaint.exe");
                    break;
                case "cmd":
                    System.Diagnostics.Process.Start("cmd.exe");
                    break;
                default:
                    break;
            }

        }
        private void about_click(object sender, RoutedEventArgs e)
        {
            AboutWindow abW = new AboutWindow();
            LoadingAdorner.IsAdornerVisible = true;
            abW.ShowDialog();
            LoadingAdorner.IsAdornerVisible = false;
        }


        DateTime dt;
        public void Mess(string str)
        {
            dt = DateTime.Now;
            string strd ="\r\n"+ dt.Date.Month + "-" + dt.Date.Day;
            strd = strd+"  "+ dt.Hour + ":" + dt.Minute;
            strd = strd + " : " + str;
            this.Dispatcher.Invoke(new Action(() => {
                dispMess.AppendText(strd);
            }));
        }


    }









    public class SocketClient
    {

        public bool isConncet=false;
        Thread Th;

        public delegate void DelegateMessage(string str);
        public event DelegateMessage OnmessageEvent;

        Socket socketSend;

        bool ThRun = false;
       public bool Connect()//连接
        {
            if (ThRun)
            {
                return true;
            }
            else
            {
                Th = new Thread(new ThreadStart(ConnectRun));
                Th.IsBackground = true;
                Th.Start();
                return true;
            }
            //try
            //{
            //    //创建负责通信的Socket
            //    socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //    IPAddress ip = IPAddress.Parse("127.0.0.1");
            //    IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32("500"));
            //    //获得要连接的远程服务器应用程序的IP地址和端口号
            //    socketSend.Connect(point);
  

            //    //开启一个新的线程不停的接收服务端发来的消息
            //    Thread th = new Thread(Recive);
            //    th.IsBackground = true;
            //    th.Start();
            //    isConncet = true;
            //    return true;
            //}
            //catch
            //{
            //    isConncet = false;
            //    return false;
            //}
        }


        void ConnectRun()
        {
            ThRun = true;
            while (true)
            {             
                if (isConncet)
                {
                    Thread.Sleep(500);
                }
                else
                {
                    try
                    {
                        //创建负责通信的Socket
                        socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        IPAddress ip = IPAddress.Parse("127.0.0.1");
                        IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32("500"));
                        //获得要连接的远程服务器应用程序的IP地址和端口号
                        socketSend.Connect(point);


                        //开启一个新的线程不停的接收服务端发来的消息
                        Thread th = new Thread(Recive);
                        th.IsBackground = true;
                        th.Start();
                        isConncet = true;
                       
                    }
                    catch
                    {
                        isConncet = false;
                        
                    }
                }
            }
        }
        void Recive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    int r = socketSend.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    string s = Encoding.UTF8.GetString(buffer, 0, r);
                    OnmessageEvent?.Invoke(s);
                }
                catch
                {
                    isConncet = false;
                }
                
            }
            isConncet = false;
        }

       public void Send(string str)//发送
        {
            try
            {
                if (!isConncet)
                {
                    Connect();
                }
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
            }
            catch 
            {

                MessageBox.Show("通信助手未打开");
            }

        }
    }
 





}
